<!-- 该页面为组件切换 -->
<template>
  <!-- <a-form @validate="handleValidate" :model="sendData" ref="formRef"> -->
  <div class="bigdiv">
    <a-spin :spinning="spinnings" :delay="0">
      <a-form ref="formRef" :model="sendData">
        <ul class="bigul1">
          <li class="fitstfont">数据资产表基础信息</li>
          <li class="secoundfont"
            ><a-form-item has-feedback label="中文名称" name="assetsName" :rules="{ required: true, validator: validateinputcontentvalueName, trigger: 'change' }"
              ><a-input v-model:value="sendData.assetsName" style="width: 700px" placeholder="请输入中文名称" allow-clear /></a-form-item
          ></li>
          <li class="secoundfont"
            ><a-form-item has-feedback label="英文名称" name="assetsEnglish" :rules="{ required: true, validator: validateinputcontentvalueEnglish, trigger: 'change' }">
              <a-input v-model:value="sendData.assetsEnglish" style="width: 700px" placeholder="请输入英文名称" /></a-form-item
          ></li>
          <li class="secoundfont" style="margin-left: 40px"
            ><a-form-item has-feedback label="数据资产表描述"><a-input v-model:value="sendData.assetsMsg" style="width: 700px; height: 80px" placeholder="请输入资产表描述" /></a-form-item
          ></li>
          <li class="secoundfont">
            <a-form-item :has-feedback="false" label="所属目录" name="dataSource" :rules="{ required: true, validator: validateinputcontentsDirname, trigger: 'change' }">
              <a-table bordered :data-source="sendData.dataSource" :columns="columns" :pagination="false">
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.title === '所属目录'">
                    <a-cascader
                      v-model:value="record.value"
                      :options="options"
                      :show-search="{ filter }"
                      placeholder="请选择需要添加到的目录"
                      :field-names="{ label: 'directoryName', value: 'directoryId', children: 'children' }"
                    />
                    <!-- <a-alert message="Error" type="error" :show-icon="true" /> -->
                  </template>
                  <template v-if="column.title === '操作' && index != 0">
                    <a-button @click="delt(index)">删除</a-button>
                  </template>

                  <template v-if="column.title === '操作' && index == 0">
                    <a-button disabled>删除</a-button>
                  </template>
                </template>

                <template #summary>
                  <a-table-summary-row>
                    <a-table-summary-cell :col-span="2"><a-button style="width: 100%" @click="addCongifTable">添加</a-button></a-table-summary-cell>
                  </a-table-summary-row>
                </template>
              </a-table>
              <div v-if="showError" style="color: red">输入为空请重新输入</div>
            </a-form-item>
          </li>
        </ul>
      </a-form>
      <a-form ref="formRef2" :model="sendData">
        <div>
          <ul class="bigul1">
            <li class="fitstfont">数据资产表字段添加</li>
            <li>
              <a-table :columns="columns2" :data-source="sendData.assetsValueList">
                <template #bodyCell="{ column, record, text, index }">
                  <template v-if="['valueName', 'valueEnglish', 'valueMsg', 'standardId'].includes(column.dataIndex)">
                    <div>
                      <a-form-item
                        v-if="editableData[record.code] && !(column.title == '标准映射')"
                        has-feedback
                        :name="['editableData1', record.code, column.dataIndex]"
                        :rules="{ required: true, validator: column.func }"
                      >
                        <a-input v-model:value="editableData[record.code][column.dataIndex]" placeholder="请输入" :maxlength="10" style="margin: -5px 0" />
                      </a-form-item>

                      <template v-if="!editableData[record.code] && !(column.title == '标准映射')">
                        <span style="display: inline-block; width: 195px">{{ text }}</span>
                      </template>

                      <template v-if="!editableData[record.code] && column.title == '标准映射'">
                        <!-- <a-form-item   v-if="!(editableData[record.code])&&column.title=='标准映射'" has-feedback :name="['assetsValueList',record.code,column.dataIndex]"  :rules="{required: true,validator:validatedirectoryIdList,}" > -->
                        <a-select
                          v-model:value="record.standardId"
                          show-search
                          placeholder="请选择或者查询对应资产号"
                          style="width: 200px"
                          :options="standdataRef"
                          :filter-option="filterOption"
                          :field-names="{ label: 'label', value: 'standardId' }"
                          :disabled="record.isdisabled"
                        ></a-select>
                      </template>
                      <a-form-item
                        v-else-if="column.title == '标准映射'"
                        has-feedback
                        :name="['assetsValueList', record.code, column.dataIndex]"
                        :rules="{ required: true, validator: validatedirectoryIdList }"
                      >
                        <a-select
                          v-model:value="record.standardId"
                          show-search
                          placeholder="请选择或者查询对应资产号"
                          style="width: 200px"
                          :options="standdataRef"
                          :filter-option="filterOption"
                          :field-names="{ label: 'label', value: 'standardId' }"
                          :disabled="record.isdisabled"
                        ></a-select>
                      </a-form-item>
                    </div>
                  </template>
                  <template v-if="column.title === '操作'">
                    <div class="editable-row-operations">
                      <span v-if="editableData[record.code]">
                        <a-typography-link @click="save(record.code, record, column)">保存</a-typography-link>
                        <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.code)">
                          <a style="margin-left: 10px">取消更改</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <a @click="edit(record.code, record)">编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;
                        <a @click="deltassetsValueList(index)">删除</a>
                      </span>
                    </div>
                  </template>
                </template>

                <template #summary>
                  <a-table-summary-row>
                    <a-table-summary-cell :col-span="5" @click="addAssetsFiled"><a-button style="width: 100%">添加</a-button></a-table-summary-cell>
                  </a-table-summary-row>
                </template>
              </a-table>
            </li>
          </ul>
        </div>
      </a-form>
      <footer style="margin-top: 200px; margin-bottom: 50px; text-align: center">
        <a-button @click="cancelpage">取消</a-button>
        <a-button style="margin-left: 10px" @click="commit">提交</a-button>
        <a-button style="margin-left: 10px" @click="test">显示</a-button>
      </footer>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
  import { defineComponent, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { CascaderProps, Form, FormInstance, SelectProps, message } from 'ant-design-vue';
  import type { ShowSearchType } from 'ant-design-vue/es/cascader';
  import { any, number, string } from 'vue-types';
  import { cloneDeep } from 'lodash-es';
  import type { UnwrapRef } from 'vue';
  import { useStore } from '@/store';
  import { AddAsset, getStandDataApi, querySingleapi, UpdateAssetContentDataApi } from '../../api/test/asset';
  import { addAssetsSendData, tablefileds, tableconfig } from './assetType';
  import { mit } from '@/utils/assetMittConfig';
  import { Rule } from 'ant-design-vue/es/form/interface';
  import { validateinputcontentvalueName, validateinputcontentvalueEnglish, validateinputcontentvalueMsg, validateinputcontentstandardId } from './check';
  const showError = ref();
  const spinnings = ref(false);
  const store = useStore();
  const rounte = useRoute();
  const rounter = useRouter();
  const standdataRef: any = ref({});
  const formRef = ref<FormInstance>();
  const formRef2 = ref<FormInstance>();
  let options = ref(); //options
  let state: any = rounte.query.state; //标识状态
  let key = 0; //标识id
  let sendDatax: addAssetsSendData = {
    assetsId: 0,
    assetsName: '',
    assetsEnglish: '',
    assetsMsg: '',
    directoryIdList: [],
    assetsValueList: [],
    editableData1: {},
    dataSource: [],
  };
  let recursionarr: any = [];

  options.value = store.test;
  let sendData = ref(sendDatax);
  const editableData: UnwrapRef<Record<string, DataItem>> = reactive([]);
  sendData.value.editableData1 = editableData;

  //获取资产标准表
  const getStanddata = async () => {
    let a = await getStandDataApi();
    let arr: any = [];
    a.data.forEach((li: any) => {
      li.label = li.standardId + '-' + li.standardName + '-' + li.standardMsg;
      if (li.standardStatus == 2) {
        arr.push(li);
      }
    });

    standdataRef.value = arr;
  };
  getStanddata();
  standdataRef.value = [];
  //根据详细信息查询
  const searchByid = async (id: any) => {
    let a = await querySingleapi(id);
    console.log('得到数据', a.data);
    sendData.value.assetsId = a.data.assetsId;
    sendData.value.assetsName = a.data.assetsName;
    sendData.value.assetsEnglish = a.data.assetsEnglish;
    sendData.value.assetsMsg = a.data.assetsMsg;
    a.data.directoryName.forEach((li: any) => {
      recursion(li);

      sendData.value.dataSource.push({
        catelog: '',
        code: 0,
        value: recursionarr,
      });
      recursionarr = [];
    });
    a.data.valueList.forEach((li: any) => {
      let ob = { valueId: li.valueId, valueName: li.valueName, valueEnglish: li.valueEnglish, valueMsg: li.valueMsg, code: key++, isdisabled: true, standardId: li.standardId };
      sendData.value.assetsValueList.push(ob);
    });
    console.log('编辑详细', sendData.value);
  };

  //递归处理
  const recursion = (li: any) => {
    if (li.children == []) {
      recursionarr.push(li.directoryId);
      return;
    }
    recursionarr.push(li.directoryId);
    li.children.forEach((cd: any) => {
      recursion(cd);
    });
  };

  if (state == '编辑') {
    searchByid(rounte.query.id);
  } else {
    sendData.value.dataSource.push({ catelog: '', code: 0, value: [] });
  }

  //定义表一字段名称
  const columns = ref([
    {
      title: '所属目录',
      dataIndex: 'catelog',
      key: '1',
    },
    {
      title: '操作',
      key: '2',
    },
  ]);
  //表一数据源

  //选择搜索的过滤器
  const filter: ShowSearchType['filter'] = (inputValue, path) => {
    return path.some(option => option.directoryName.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
  };
  let validateinputcontentsDirname = async (_rule: Rule, value: any) => {
    for (let i = 0; i <= value.length - 1; i++) {
      if (value[i].value == undefined) {
        showError.value = true;
        break;
      } else if (value[i].value[0] == null) {
        showError.value = true;
        break;
      } else {
        showError.value = false;
      }
    }
  };

  //定义表2的数据和行列
  const columns2 = ref([
    {
      title: '字段中文名称',
      dataIndex: 'valueName',
      func: validateinputcontentvalueName,
    },
    {
      title: '字段英文名称',
      dataIndex: 'valueEnglish',
      func: validateinputcontentvalueEnglish,
    },
    {
      title: '字段说明',
      dataIndex: 'valueMsg',
      func: validateinputcontentvalueMsg,
    },
    {
      title: '标准映射',
      dataIndex: 'standardId',
      func: validateinputcontentstandardId,
    },
    {
      title: '操作',
      dataIndex: 'howdo',
    },
  ]);
  //删除
  const delt = (key: any) => {
    sendData.value.dataSource.splice(key, 1);
  };
  const deltassetsValueList = (key: any) => {
    console.log(key);
    sendData.value.assetsValueList.splice(key, 1);
    console.log(sendData.value.assetsValueList);
  };
  //添加目录配置表
  const addCongifTable = () => {
    sendData.value.dataSource.push({
      catelog: '',
      code: 0,
      value: [],
    });
  };

  //添加数据资产字段sendData.value.editableData1[sendData.value.editableData1.length-1].isdisabled
  const addAssetsFiled = () => {
    if (sendData.value.editableData1[sendData.value.editableData1.length - 1] == null) {
      sendData.value.assetsValueList.push({ valueId: 0, valueName: '', valueEnglish: '', valueMsg: '', standardId: '', code: key, isdisabled: false });
      edit(key++);
    } else {
      message.info('请先对当前数据进行保存');
    }
  };

  const edit = (key: number, record?: any) => {
    editableData[key] = cloneDeep(sendData.value.assetsValueList.filter((item: { code: number }) => key === item.code)[0]);
    if (record != null) {
      record.isdisabled = false;
    }
  };
  const save = async (key: number, record?: any, column?: any) => {
    let haveerror = false;
    await formRef2.value
      .validate()
      .then(() => {
        console.log('ok');
      })
      .catch(() => {
        haveerror = true;
      });
    if (!haveerror) {
      console.log(formRef.value);
      editableData[record.code]['standardId'] = record.standardId;
      Object.assign(sendData.value.assetsValueList.filter((item: { code: number }) => key === item.code)[0], editableData[key]);
      delete editableData[key];
      if (record != null) {
        record.isdisabled = true;
      }
    }
  };
  const cancel = (key: number) => {
    sendData.value.assetsValueList.splice(key, 1);
    delete editableData[key];
  };

  // 提交请求
  const commit = async () => {
    let iserror = 2;
    spinnings.value = true;
    let b = await formRef.value.validateFields().catch(() => {
      formRef.value.scrollToField();
      iserror--;
    });
    await formRef2.value.validateFields().catch(() => {
      iserror--;
    });
    if (iserror == 2) {
      let a: any;
      console.log('b', b);
      sendData.value.dataSource.forEach((li: any) => {
        sendData.value.directoryIdList.push(li.value[li.value.length - 1]);
      });
      console.log('提交数据', sendData.value);
      if (state == '编辑') {
        a = await UpdateAssetContentDataApi(sendData.value);
        if (a.code == 100500) {
          message.info('修改失败');
        } else {
          message.info('修改成功');
          rounter.push('/home/Asset');
        }
      } else {
        a = await AddAsset(sendData.value);
        if (a.code == 100500) {
          message.info('新增失败');
        } else {
          message.info('新增成功');
          rounter.push('/home/Asset');
        }
      }
      console.log('提交返回状态', a);
    }
    spinnings.value = false;
  };

  //数据标准映射过滤
  const filterOption = (input: string, option: any) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  //传入目录数据
  //取消返回上级目录
  const cancelpage = () => {
    rounter.go(-1);
  };

  let validatedirectoryIdList = async (_rule: Rule, value: any) => {
    console.log('表格的', value);
    if (value === '') {
      return Promise.reject('输入为空请重新输入');
    }
  };
  const test = () => {
    console.log(sendData.value);
  };
</script>
<style lang="less" scoped>
  li {
    list-style: none;
  }

  .bigdiv {
    margin-top: 20px;
  }

  .bigul1 > li:nth-child(n + 2) {
    display: flex;
    margin-left: 80px;
  }

  .bigul1 > li {
    margin-bottom: 20px;
  }

  .fitstfont {
    font-size: larger;
    font-weight: bolder;
  }

  .secoundfont {
    font-size: larger;
  }
</style>
